//本JS的方法目前仅适用于ETH链
import {
	Wallet,
	providers,
	parseEther
} from "ethers";

//新增ETH地址创建一个新的钱包地址，私钥，助记词
export const generateEthereumWallet = () => {
	// 使用 createRandom 生成随机钱包
	const wallet = Wallet.createRandom();
	console.log("钱包名称:", wallet.mnemonic.phrase);
	console.log("助记词:", wallet.mnemonic.phrase);
	console.log("钱包地址:", wallet.address);
	console.log("私钥:", wallet.privateKey);
	
	return {
		mnemonic: wallet.mnemonic.phrase,
		address: wallet.address,
		privateKey: wallet.privateKey,
	};
}

// generateEthereumWallet();
//使用私钥导入钱包或助记词导入钱包

export const importWallet = ({privateKey,mnemonic,path = "m/44'/60'/0'/0/0"}) => {
	try {
		let wallet;

		if (privateKey) {
			// 使用私钥导入钱包
			wallet = new Wallet(privateKey);
		} else if (mnemonic) {
			// 使用助记词导入钱包（支持路径）
			wallet = Wallet.fromPhrase(mnemonic, undefined, path);
		} else {
			throw new Error("必须提供私钥或助记词");
		}

		console.log("导入的钱包地址:", wallet.address);
		return wallet;
	} catch (error) {
		console.error("钱包导入失败:", error.message);
		return null;
	}
}

// // 示例：通过私钥导入
// const privateKey = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
// const walletFromPrivateKey = importWallet({ privateKey });

// // 示例：通过助记词导入
// const mnemonic = "test test test test test test test test test test test junk";
// const walletFromMnemonic = importWallet({ mnemonic });

// if (walletFromMnemonic) {
//   console.log("钱包地址:", walletFromMnemonic.address);
// }

//通过私钥进行ETH转账
export const ETHtransferEtherUsingPrivateKey = async(privateKey, recipient, amountEther, rpcUrl)=>{
	try {
		// 1. 使用私钥创建钱包实例
		const wallet = new Wallet(privateKey);

		// 2. 连接到以太坊网络（通过 RPC 节点）
		const provider = new providers.JsonRpcProvider(rpcUrl);
		const connectedWallet = wallet.connect(provider);

		console.log("钱包地址:", connectedWallet.address);

		// 3. 获取钱包余额
		const balance = await connectedWallet.getBalance();
		console.log("钱包余额:", balance.toString(), "wei");

		// 检查余额是否足够
		const amountWei = parseEther(amountEther); // 转换以太值为 wei
		if (balance.lt(amountWei)) {
			throw new Error("余额不足，无法完成转账");
		}

		// 4. 构造交易
		const tx = {
			to: recipient, // 接收方地址
			value: amountWei, // 转账金额（单位: wei）
			gasLimit: 21000, // 简单转账的 Gas 限制
			gasPrice: await provider.getGasPrice(), // 从网络动态获取 Gas 价格
		};

		console.log("交易详情:", tx);
		// 5. 签名并发送交易
		const txResponse = await connectedWallet.sendTransaction(tx);
		console.log("交易已发送，等待确认...");

		// 等待交易完成
		const receipt = await txResponse.wait();
		console.log("交易成功，交易哈希:", receipt.transactionHash);

		return receipt;
	} catch (error) {
		console.error("转账失败:", error.message);
		throw error;
	}
}
// ERC-20 标准 ABI（只需要 `transfer` 方法部分）
const ERC20_ABI = [
	"function transfer(address to, uint256 amount) public returns (bool)",
];
//通过私钥进行代币转账
export const transferToken = async(privateKey, tokenAddress, recipient, amount, rpcUrl, decimals = 18)=> {
	try {
		// 1. 使用私钥创建钱包实例
		const wallet = new Wallet(privateKey);

		// 2. 连接到以太坊网络（通过 RPC 提供商）
		const provider = new providers.JsonRpcProvider(rpcUrl);
		const connectedWallet = wallet.connect(provider);

		console.log("钱包地址:", connectedWallet.address);

		// 3. 连接到代币智能合约
		const tokenContract = new Contract(tokenAddress, ERC20_ABI, connectedWallet);

		// 4. 转换代币数量为最小单位（根据代币的 decimals）
		const amountInUnits = parseUnits(amount.toString(), decimals);

		console.log(`转账 ${amount} 个代币（最小单位: ${amountInUnits.toString()}）到地址: ${recipient}`);

		// 5. 调用 `transfer` 方法发送代币
		const txResponse = await tokenContract.transfer(recipient, amountInUnits);

		console.log("交易已发送，等待确认...");
		console.log("交易哈希:", txResponse.hash);

		// 6. 等待交易确认
		const receipt = await txResponse.wait();
		console.log("交易成功，交易哈希:", receipt.transactionHash);

		return receipt;
	} catch (error) {
		console.error("代币转账失败:", error.message);
		throw error;
	}
}

// 示例：调用代币转账函数
const privateKey = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; // 替换为您的私钥
const tokenAddress = "0xTokenContractAddressHere"; // 替换为代币合约地址（ERC-20）
const recipient = "0xRecipientAddressHere"; // 替换为接收方地址
const amount = "10"; // 转账的代币数量
const rpcUrl = "https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY"; // 替换为您的以太坊 RPC 节点 URL
const decimals = 18; // 代币的小数位（如 ERC-20 通常是 18）

// transferToken(privateKey, tokenAddress, recipient, amount, rpcUrl, decimals)
//   .then((receipt) => console.log("代币交易完成:", receipt))
//   .catch((error) => console.error("代币交易失败:", error.message));